package cn.turboinfo.dongying.api.domain.admin.usecase.agencies;

import cn.turboinfo.dongying.api.domain.common.service.agencies.AgenciesService;
import cn.turboinfo.dongying.api.domain.common.service.division.DivisionService;
import cn.turboinfo.dongying.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.dongying.api.entity.common.pojo.agencies.Agencies;
import cn.turboinfo.dongying.api.entity.common.pojo.division.Division;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QPage;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.response.QResponse;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class AgenciesSearchUseCase extends AbstractUseCase<AgenciesSearchUseCase.InputData, AgenciesSearchUseCase.OutputData> {
    private final AgenciesService agenciesService;

    private final DivisionService divisionService;

    @Override
    protected OutputData doAction(InputData inputData) {

        QResponse<Agencies> response = agenciesService.findAll(inputData.getRequest(), inputData.getRequestPage());

        Set<Long> areaCodeSet = response.getPagedData().stream()
                .map(Agencies::getAreaCode)
                .collect(Collectors.toSet());

        Map<Long, Division> divisionMap = divisionService.findByIdCollection(areaCodeSet)
                .stream()
                .collect(Collectors.toMap(Division::getId, division -> division));

        response.getPagedData().stream()
                .peek(it -> it.setAreaName(divisionMap.get(it.getAreaCode()).getAreaName()))
                .toList();

        return OutputData.builder()
                .qResponse(response)
                .build();
    }

    @Getter
    @Setter
    @Builder
    public static class InputData extends AbstractUseCase.InputData {
        private QRequest request;

        private QPage requestPage;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private QResponse<Agencies> qResponse;
    }

}
